// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

package com.netease.yunxin.app.im.message;

import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.yunxin.kit.chatkit.model.CustomAttachment;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 商品消息附件
 */
public class ProductAttachment extends CustomAttachment {

    private static final String TAG = "ProductAttachment";
    private static final String KEY_PRODUCT_ID = "product_id";
    private static final String KEY_PRODUCT_NAME = "product_name";
    private static final String KEY_PRODUCT_PRICE = "product_price";
    private static final String KEY_PRODUCT_IMAGE = "product_image";
    private static final String KEY_PRODUCT_DESC = "product_desc";
    private static final String KEY_PRODUCT_URL = "product_url";

    private String productId;
    private String productName;
    private String productPrice;
    private String productImage;
    private String productDesc;
    private String productUrl;

    public ProductAttachment() {
        super(1000); // 使用自定义类型值，避免与系统内置类型冲突
        Log.d(TAG, "ProductAttachment() 构造, type=1000");
    }

    public ProductAttachment(String productId, String productName, String productPrice,
                           String productImage, String productDesc, String productUrl) {
        super(1000);
        this.productId = productId;
        this.productName = productName;
        this.productPrice = productPrice;
        this.productImage = productImage;
        this.productDesc = productDesc;
        this.productUrl = productUrl;
        Log.d(TAG, "ProductAttachment(带参数) 构造, type=1000, productName=" + productName);
    }

    @Override
    public void parseData(@Nullable JSONObject json) {
        Log.d(TAG, "parseData called, data: " + (json != null ? json.toString() : "null"));
        try {
            if (json != null) {
                JSONObject data = json.optJSONObject("data");
                if (data != null) {
                    productId = data.optString(KEY_PRODUCT_ID, "");
                    productName = data.optString(KEY_PRODUCT_NAME, "");
                    productPrice = data.optString(KEY_PRODUCT_PRICE, "");
                    productImage = data.optString(KEY_PRODUCT_IMAGE, "");
                    productDesc = data.optString(KEY_PRODUCT_DESC, "");
                    productUrl = data.optString(KEY_PRODUCT_URL, "");
                    Log.d(TAG, "parseData success: " + toString());
                } else {
                    Log.e(TAG, "parseData: data field is null");
                    // 尝试直接从json中解析，可能没有嵌套的data字段
                    productId = json.optString(KEY_PRODUCT_ID, "");
                    productName = json.optString(KEY_PRODUCT_NAME, "");
                    productPrice = json.optString(KEY_PRODUCT_PRICE, "");
                    productImage = json.optString(KEY_PRODUCT_IMAGE, "");
                    productDesc = json.optString(KEY_PRODUCT_DESC, "");
                    productUrl = json.optString(KEY_PRODUCT_URL, "");
                    Log.d(TAG, "parseData fallback success: " + toString());
                }
            } else {
                Log.e(TAG, "parseData: json is null");
            }
        } catch (Exception e) {
            Log.e(TAG, "parseData error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 从字符串解析数据
     */
    public void parseDataFromString(@Nullable String jsonStr) {
        Log.d(TAG, "parseDataFromString called, data: " + jsonStr);
        try {
            if (jsonStr != null && !jsonStr.trim().isEmpty()) {
                JSONObject json = new JSONObject(jsonStr);
                parseData(json);
            } else {
                Log.e(TAG, "parseDataFromString: jsonStr is null or empty");
            }
        } catch (JSONException e) {
            Log.e(TAG, "parseDataFromString JSONException: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            Log.e(TAG, "parseDataFromString error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Nullable
    @Override
    protected JSONObject packData() {
        try {
            JSONObject data = new JSONObject();
            data.put(KEY_PRODUCT_ID, productId);
            data.put(KEY_PRODUCT_NAME, productName);
            data.put(KEY_PRODUCT_PRICE, productPrice);
            data.put(KEY_PRODUCT_IMAGE, productImage);
            data.put(KEY_PRODUCT_DESC, productDesc);
            data.put(KEY_PRODUCT_URL, productUrl);

            JSONObject result = new JSONObject();
            result.put("type", getType());
            result.put("data", data); // 关键：嵌套 data 字段

            Log.d(TAG, "packData: " + result.toString());
            return result;
        } catch (JSONException e) {
            Log.e(TAG, "packData error: " + e.getMessage());
            return null;
        }
    }

    @NonNull
    @Override
    public String toJsonStr() {
        JSONObject data = packData();
        String jsonStr = data != null ? data.toString() : "{}";
        Log.d(TAG, "toJsonStr: " + jsonStr);
        return jsonStr;
    }

    // Getters
    public String getProductId() { return productId; }
    public String getProductName() { return productName; }
    public String getProductPrice() { return productPrice; }
    public String getProductImage() { return productImage; }
    public String getProductDesc() { return productDesc; }
    public String getProductUrl() { return productUrl; }

    @Override
    public String toString() {
        return "ProductAttachment{" +
                "productId='" + productId + '\'' +
                ", productName='" + productName + '\'' +
                ", productPrice='" + productPrice + '\'' +
                ", productImage='" + productImage + '\'' +
                ", productDesc='" + productDesc + '\'' +
                ", productUrl='" + productUrl + '\'' +
                '}';
    }
}